<template>
	<view class="content">
		<view class="caption"> 产品图片 </view>
		<view class="cu-form-group upload">
			<view class="solids" @tap="ChooseImage()">
				<image mode="aspectFill" :src="imgList"></image>
			</view>
		</view>
		<view class="caption"> 产品基本信息 </view>
		<view class="cu-form-group">
			<view class="title">名称</view>
			<input v-model="productName" placeholder="请填写产品名称" name="input" type="text"></input>
		</view>
		<view class="cu-form-group">
			<view class="title">价格</view>
			<input  v-model="productPrice" type="text" placeholder="请输入价格" name="input"></input>
		</view>
		<view class="cu-form-group"  @tap="showModal" data-target="bottomModal">
			<view class="title">可选员工</view>
			<input v-model="employeeIdsN" placeholder="请选择员工" name="input" disabled="disabled"></input>
			<view class="lg text-gray cuIcon-right">
			</view>
		</view>
		<view class="cu-form-group">
			<view class="title">是否上架</view>
			 <switch :checked="productShelves == 0" @change="switchChange"/>
			 <!-- <switch v-else @change="switchChange1"/> -->
		</view>
		<view class="next" @tap="addProduct()">
			<view class="next2">确认</view>
		</view>
		<!-- 店铺弹出模态框 -->
		<view class="cu-modal bottom-modal" :class="modalName=='bottomModal'?'show':''">
			<view class="cu-dialog  bg-white">
				<view class="cu-bar">
					<view class="action choose-staff">选择员工</view>
					<view class="action cuIcon-roundclosefill qxmd" @tap="hideModal"></view>
				</view>
				<scroll-view scroll-y="true" show-scrollbar="true" scroll-top="0" class="product-modal">
					<view class="index-flex-row flex-item-center _flex_row product-list" v-for="(item,index) in staffList">
						<view class="product-info _flex_row">
							<image :src="item.image" mode="aspectFill"></image>
							<text>{{item.name}}</text>
						</view>
						<view class="flex-item-center checkbox"  @tap='chooseStaff(item.id,item.name)'>
							<image style="width: 44rpx; height: 44rpx;" src="../../../static/images/honggou.png" v-if="chooseStaffList.includes(item.id)"></image>
							<image style="width: 44rpx; height: 44rpx;" src="../../../static/images/huiyuanquan.png" v-else></image>
						</view>
					</view>
					<uni-load-more :status="loadingType"></uni-load-more>
				</scroll-view>
				<view class="next">
					<view class="next3" @tap="add()">确认</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {showStaffList,addProduct,showStaffListById} from '@/api/index.js';
	import tuiModal from "@/components/modal/modal"//弹窗
	import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
	import config from '@/config/index';
	var _self,
	pageSize = 10,
	currentPage = 1;
	export default {
		components: {
			tuiModal,
			uniLoadMore
		},
		data() {
			return {
				imgList: '../../../static/images/addPic.png',
				staffList:[],//员工列表
				chooseStaffnewList:[],//选择员工列表根据id
				chooseStaffList:[],//选择员工
				employeeIds:'',//员工id
				productId:null,//产品id
				productName:null,//产品名称
				productPrice:null,//产品价格
				productShelves:0,//产品状态
				keywords:'',//关键字
				modalName: null,
				payType: 'wxpay',
				loadingType: 'more', //加载更多状态
				productInfo:{},//产品信息
				chooseStaffListN:[],
				employeeIdsN:'',
			}
		},
		onLoad(options) {
			_self = this;
			// =uni.getStorageSync('productInfo');
			console.log(options.item);
			if(options.item != undefined){
				_self.productInfo = JSON.parse(options.item);
				console.log(_self.productInfo.id)
			}
			if(_self.productInfo.id!=undefined){
				this.productId=_self.productInfo.id;
				_self.imgList = _self.productInfo.imgs
				_self.productName = _self.productInfo.name
				_self.productPrice = _self.productInfo.price
				_self.productShelves = _self.productInfo.shelves
				_self.showStaffListById();//获取员工列表
			}
			currentPage=1;
			_self.staffList = [];
			_self.getStaffInfo();//获取员工列表
		},
		onPullDownRefresh: function() {
		 	_self.getStaffInfo();//获取员工列表
		},
		//上拉加载收据
		onReachBottom: function() {
			if(_self.loadingType == 'nomore'){
				return false
			}
			currentPage++;
			_self.getStaffInfo();//获取员工列表
		},
		methods: {
			//添加产品按钮
			add(){
				this.employeeIds = ''
				this.employeeIdsN = ''
				this.modalName = null
				this.employeeIds = this.chooseStaffList.toString()
				this.employeeIdsN = this.chooseStaffListN.toString()
			},
			//根据产品id查询员工
			showStaffListById(){
				let _that = this
				showStaffListById(currentPage,pageSize,_that.productId).then(re =>{
					if(re.length < pageSize){
						_self.loadingType = 'nomore';
					}else{
						_self.loadingType = 'more'
					}
					if (re== '') {//没有数据
						_self.loadingType = 'nomore';
						uni.hideNavigationBarLoading();//关闭加载动画
						uni.stopPullDownRefresh();//得到数据后停止下拉刷新
						return;
					}
					if(currentPage==1){
						_self.chooseStaffnewList = re
					}else{
						_self.chooseStaffnewList = _self.chooseStaffnewList.concat(re);//将数据拼接在一起
					}
					_self.chooseStaffList = []
					_self.chooseStaffListN = []
					_self.chooseStaffnewList.map((v,i)=>{
						_self.chooseStaffList.push(v.id)
						_self.chooseStaffListN.push(v.name)
					})
					this.employeeIds = ''
					this.employeeIdsN = ''
					_self.employeeIds = _self.chooseStaffList.toString()
					_self.employeeIdsN = _self.chooseStaffListN.toString()
					uni.hideNavigationBarLoading();
					uni.stopPullDownRefresh();//得到数据后停止下拉刷新
				}).catch(re=>{
					console.log(re);
				});
			},
			//增加产品
			addProduct(){
				// uni.removeStorage({ key: 'productInfo'});
				let _that = this
				this.modalName = null
				// console.log(_that.productShelves);
				addProduct(_that.employeeIds,_that.productId,_that.imgList,_that.productName,_that.productPrice,_that.productShelves).then(re =>{
					if(_that.productId!=undefined){
						uni.showToast({
						    title: '编辑产品成功',
						    duration: 2000
						});
					}else{
						uni.showToast({
						    title: '添加产品成功',
						    duration: 2000
						});
					}
					setTimeout(function(){
						uni.navigateBack({
						    delta: 1
						});
					},2000)
				}).catch(re=>{
					console.log(re);
				});
			},
			//stwich切换
			switchChange: function (e) {
				let _that = this
				if(e.target.value == true){
					_that.productShelves = 0
				}else{
					_that.productShelves = 1
				}
			},
			// switchChange1: function (e) {
			// 	let _that = this
			// 	if(e.target.value == true){
			// 		_that.productShelves = 0
			// 	}else{
			// 		_that.productShelves = 1
			// 	}
			// },
			//选择员工
			chooseStaff(id,name){
				if (this.chooseStaffList.includes(id)) {
					this.chooseStaffList.splice(this.chooseStaffList.findIndex((item) => (item == id)), 1)
				} else {
					this.chooseStaffList.push(id)
				}
				console.log(this.chooseStaffListN.includes(name)+'这是否正常',name)
				if (this.chooseStaffListN.includes(name)) {
					this.chooseStaffListN.splice(this.chooseStaffListN.findIndex((item) => (item == name)), 1)
				} else {
					this.chooseStaffListN.push(name)
				}
				console.log(this.chooseStaffListN);
			},
			//获取员工列表
			getStaffInfo(){
				showStaffList(_self.keywords,currentPage,pageSize).then(re =>{
					if(re.length < pageSize){
						_self.loadingType = 'nomore';
					}else{
						_self.loadingType = 'more'
					}
					if (re== '') {//没有数据
						_self.loadingType = 'nomore';
						uni.hideNavigationBarLoading();//关闭加载动画
						uni.stopPullDownRefresh();//得到数据后停止下拉刷新
						return;
					}
					if(currentPage==1){
						_self.staffList = re
					}else{
						_self.staffList = _self.staffList.concat(re);//将数据拼接在一起
					}
					uni.hideNavigationBarLoading();
					uni.stopPullDownRefresh();//得到数据后停止下拉刷新
				}).catch(re=>{
				});
			},
			//页面跳转
			toPage(page){
				uni.navigateTo({
					url:page
				});
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			ChooseImage: async function() {
				let _that  = this
				uni.chooseImage({
					count: 4, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success(res) {
						// 获得临时路径 
						var tempFilePath = res.tempFilePaths;
						uni.uploadFile({
							url: config.requestUrl + '/uploadCt/uploadImg',
							filePath: tempFilePath[0],
							name: 'file',
							header:{
								'Content-Type': 'application/x-www-form-urlencoded',
								'userToken':uni.getStorageSync('token'),
							},
							success: (res) => {
								let json = JSON.parse(res.data)
								_that.imgList=json.result.imgSrc;
							}
						});
					}
				});
			},
			async checkPermission(code) {
			    let type = code ? code - 1 : this.sourceTypeIndex;
			    let status = permision.isIOS ? await permision.requestIOS(sourceType[type][0]) :
			        await permision.requestAndroid(type === 0 ? 'android.permission.CAMERA' :
			            'android.permission.READ_EXTERNAL_STORAGE');
			
			    if (status === null || status === 1) {
			        status = 1;
			    } else {
			        uni.showModal({
			            content: "没有开启权限",
			            confirmText: "设置",
			            success: function(res) {
			                if (res.confirm) {
			                    permision.gotoAppSetting();
			                }
			            }
			        })
			    }
			    return status;
			},
			ViewImage(e) {
				uni.previewImage({
					urls: this.imgList,
					current: e.currentTarget.dataset.url
				});
			},
			DelImg(e) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这张图片吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							this.imgList.splice(e.currentTarget.dataset.index, 1)
						}
					}
				})
			},
			goBack(){
				uni.navigateBack({
				    delta: 1
				});
			},
			// 弹窗
			showModal(e) {
				let _that = this
				_that.employeeIds = ''
				_that.employeeIdsN = ''
				_self.chooseStaffList = []
				_self.chooseStaffListN = []
				if(_that.productInfo.id!=undefined){
					this.showStaffListById();
				}
				this.modalName = e.currentTarget.dataset.target
			},
			hideModal(e) {
				this.modalName = null
			},
		}
	}
</script>

<style>
	.caption{color: #424242;font-weight: 600;padding:24rpx;}
	.upload{padding:11rpx;}
	.cu-form-group input{text-align: right;}
	.next{
		margin:0 76rpx;
	}
	.next .next2{
		background: url("../../../static/images/band-card.png") no-repeat;
		background-size: 100% 100%;
		color: #fff;	
		width:600rpx;
		height:80rpx;
		margin:130rpx auto 0;
		line-height: 80rpx;
		text-align: center;
		font-size: 28rpx;
	}
	.next .next3{
		background: url("../../../static/images/band-card.png") no-repeat;
		background-size: 100% 100%;
		color: #fff;	
		width:600rpx;
		height:80rpx;
		line-height: 80rpx;
		text-align: center;
		font-size: 28rpx;
		position: fixed;
		bottom: 60rpx;
	}
	.choose-staff {
		font-family: PingFangSC-regular;
		text-align: left;
		font-size: 13px;
		color: rgba(106, 106, 106, 1);
	}
	.cu-dialog{
		height:932rpx;
	}
	.product-modal{
		height:690rpx;
		overflow-y: scroll;
	}
	.qxmd {
		width: 50rpx;
		height: 50rpx;
		color: rgba(189, 189, 189, 1);
		font-size: 50rpx;
	}
	.product-list{
		height: 140rpx;
		align-items: center;
		padding:0 30rpx;
	}
	.product-info{
		flex: 1;
		align-items: center;
	}
	.product-info image{
		border: 1px solid #F5F5F5;
		border-radius: 100rpx;
		width:100rpx;
		height:100rpx;
		margin-right: 20rpx;
	}
	.product-info text{
		color: #3E3E3E;
		font-size: 32rpx;
		font-weight: 600;
	}
	.solids{
		width:160rpx;
		height: 160rpx;
	}
	.solids image{
		width:160rpx;
		height: 160rpx;
	}
</style>
